package com.toilet.easyvideo.config;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Map;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JWTConfig {
    /**
     * token失效时间
     */
    private Integer expireTime;
    /**
     * 鉴权头
     */
    private String header;
    /**
     * 秘钥
     */
    private String appSecret;


    /**
     * 创建指定时间的token
     *
     * @return
     */
    public String createToken(Map<String, Object> payload) {
        DateTime now = DateTime.now();
        DateTime expTime = now.offsetNew(DateField.HOUR, expireTime);
        // 签发时间
        payload.put(JWTPayload.ISSUED_AT, now);
        // 过期时间
        payload.put(JWTPayload.EXPIRES_AT, expTime);
        // 生效时间
        payload.put(JWTPayload.NOT_BEFORE, now);
        return JWTUtil.createToken(payload, appSecret.getBytes());
    }

    public JWTPayload parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        if (!jwt.setKey(appSecret.getBytes()).verify()) {
            throw new RuntimeException("token 异常");
        }

        if (!jwt.validate(0)) {
            throw new RuntimeException("token 已过期请重新登录");
        }

        return jwt.getPayload();
    }

    public Boolean verifyToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        if (!jwt.setKey(appSecret.getBytes()).verify()) {
            log.info("token 异常");
            return false;
        }
        // 验证是否过期
        return jwt.validate(0);
    }
}
